@file:Suppress("NULLABILITY_MISMATCH_BASED_ON_JAVA_ANNOTATIONS")

package com.sx.pipeline.ui

import android.graphics.Color
import android.net.Uri
import android.view.KeyEvent
import androidx.viewpager2.widget.ViewPager2
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.ToastUtils
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.util.XPopupUtils
import com.sx.mvvmlibs.utils.Logs
import com.sx.mvvmlibs.utils.RxThreadHelper
import com.sx.pipeline.R
import com.sx.pipeline.adapter.ViewPagerFmAdapter
import com.sx.pipeline.app.base.CYDataBindingBaseActivity
import com.sx.pipeline.app.config.AppConstants
import com.sx.pipeline.app.config.CommonApplyType
import com.sx.pipeline.app.config.IdentityType
import com.sx.pipeline.app.model.CYBaseViewModel
import com.sx.pipeline.arouth.RouteManager
import com.sx.pipeline.arouth.RoutePath
import com.sx.pipeline.custom.dialog.CustomBubbleAttachPopup
import com.sx.pipeline.databinding.ActMain2Binding
import com.sx.pipeline.repos.http.res.CommonApplyListVO
import com.sx.pipeline.repos.http.res.ContactUserVo
import com.sx.pipeline.repos.http.res.RongGroupVO
import com.sx.pipeline.repos.http.res.UserInfoVO
import com.sx.pipeline.ui.chat.ChatFragment
import com.sx.pipeline.ui.chat.detail.ConversationActivity
import com.sx.pipeline.ui.map.Map2Fragment
import com.sx.pipeline.ui.mine.MineFragment
import com.sx.pipeline.ui.workbench.WorkBenchFragment
import com.sx.pipeline.utils.PermissionHelper.registerRImPermissionFilter
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.schedulers.Schedulers
import io.rong.imkit.RongIM
import io.rong.imkit.utils.RouteUtils
import io.rong.imlib.RongIMClient

/**
 * @Author: YY
 * @Date: 2022/4/5
 * @Description: 主页
 */
@Route(path = RoutePath.Main.MAIN)
class Main2Activity: CYDataBindingBaseActivity<ActMain2Binding, CYBaseViewModel>(R.layout.act_main2) {

    // 触摸时间
    private var touchTime: Long = 0

    override fun initStatusBar() {

    }

    override fun initData() {
        // 初始化导航
        initNavigation()
        mViewModel.getRongAllContact()
        mViewModel.getRongGroupList()
        mViewModel.updateUserInfo()
        registerRImPermissionFilter()
    }

    override fun initListener() {
        mBinding.imageRelease.setOnClickListener {
            showSpreadDialog()
        }
    }

    /**
     * 初始化ViewPager
     */
    private fun initNavigation() {
        mBinding.navView.itemIconTintList = null
        mBinding.navView.setOnItemSelectedListener { item ->
            when (item.itemId) {
                R.id.navigation_home -> {
                    // 聊天
                    mBinding.viewPager2.setCurrentItem(0, false)
                    mBinding.navView.menu.getItem(0).isChecked = true
                }
                R.id.navigation_institutions -> {
                    // 工作台
                    mBinding.viewPager2.setCurrentItem(1, false)
                    mBinding.navView.menu.getItem(1).isChecked = true
                }
                R.id.navigation_message -> {
                    // 地图
                    mBinding.viewPager2.setCurrentItem(2, false)
                    mBinding.navView.menu.getItem(3).isChecked = true
                }
                R.id.navigation_mine -> {
                    // 我的
                    mBinding.viewPager2.setCurrentItem(3, false)
                    mBinding.navView.menu.getItem(4).isChecked = true
                }
            }
            false
        }

        mBinding.viewPager2.registerOnPageChangeCallback(object :
            ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                mBinding.navView.menu.getItem(position).isChecked = true
            }
        })

        // 设置不可滑动
        mBinding.viewPager2.isUserInputEnabled = false
        val fragments =
            arrayListOf(ChatFragment(), WorkBenchFragment(), Map2Fragment(), MineFragment())
        mBinding.viewPager2.apply {
            adapter = ViewPagerFmAdapter(supportFragmentManager, lifecycle, fragments)
            offscreenPageLimit = fragments.size
        }
        // 默认选择
        mBinding.viewPager2.setCurrentItem(1, false)
        mBinding.navView.menu.getItem(1).isChecked = true
    }

    @Suppress("DEPRECATED_IDENTITY_EQUALS")
    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        if (event.action === KeyEvent.ACTION_DOWN && KeyEvent.KEYCODE_BACK === keyCode) {
            //等待时间
            val waitTime: Long = 2000
            touchTime = if (System.currentTimeMillis() - touchTime < waitTime) {
                onBackPressed()
                return false
            } else {
                ToastUtils.showShort("再按一次退出")
                System.currentTimeMillis()
            }
            return true
        }
        return super.onKeyDown(keyCode, event)
    }

    /**
     * 点击展开
     */
    @Suppress("UNCHECKED_CAST")
    private fun showSpreadDialog() {
        val commonApplyListObservable = Observable.create<List<CommonApplyListVO?>> {
            it.onNext(mViewModel.mModel.getCacheListData(AppConstants.CacheKey.CACHE_COMMON_APPLY))
        }.subscribeOn(Schedulers.io())

        mViewModel.addSubscribe(
            commonApplyListObservable
                .compose(RxThreadHelper.rxSchedulerHelper())
                .subscribe {
                    XPopup.Builder(this)
                        .isDestroyOnDismiss(true)
                        .atView(mBinding.navView)
                        .hasShadowBg(true)
                        .isCenterHorizontal(true)
                        .asCustom(
                            CustomBubbleAttachPopup(this,
                                it as List<CommonApplyListVO>,
                                object : CustomBubbleAttachPopup.ItemClickListener {
                                    override fun onClickItem(
                                        position: Int,
                                        itemData: CommonApplyListVO
                                    ) {
                                        navigationIconUI(itemData)
                                    }
                                }).setBubbleBgColor(Color.WHITE)
                                .setArrowWidth(XPopupUtils.dp2px(this, 22f))
                                .setArrowHeight(XPopupUtils.dp2px(this, 12f))
                                .setArrowRadius(XPopupUtils.dp2px(this, 2f))
                        ).show()
                })

    }

    /**
     * 常用应用跳转
     */
    fun navigationIconUI(itemData: CommonApplyListVO) {
        when (itemData.jumpLink) {
            CommonApplyType.PUBLISHED.jumpLink -> {
                // 我发布的 - 任务
                RouteManager.Mine.intentToReleaseTaskList()
            }
            CommonApplyType.INVOLVED.jumpLink -> {
                // 我参与的 - 任务
                RouteManager.Mine.intentToParticipateTaskList()
            }
            CommonApplyType.APPROVED.jumpLink -> {
                // 我审批的 - 任务
                RouteManager.Mine.intentToApproveTaskList()
            }
            CommonApplyType.PUBLISH_TASK.jumpLink -> {
                // 发布任务
                RouteManager.Mine.intentToTaskReleaseAdd()
            }
            CommonApplyType.PUBLISH_NEEDS.jumpLink -> {
                when (mViewModel.mModel.getIdentityType()) {
                    IdentityType.OPERATING_UNIT.code -> {
                        RouteManager.Mine.intentToOperatorNeedsAdd()
                    }
                    IdentityType.BUILD_UNIT.code -> {
                        // 发布需求
                        RouteManager.Mine.intentToConstructionNeedsAdd()
                    }
                }
            }
            CommonApplyType.SUPPLY_LIST.jumpLink -> {
                // 供应列表
                RouteManager.Mine.intentToProvideInfo();
            }
            CommonApplyType.ACCOUNT.jumpLink -> {
                // 我的台账
                ARouter.getInstance().build(RoutePath.Mine.LEDGER).navigation()
            }
            CommonApplyType.BUILD_NEED_LIST.jumpLink -> {
                // 施工单位-需求列表
                RouteManager.Mine.intentToParticipationNeeds()
            }
            CommonApplyType.PUBLISH_SUPPLY.jumpLink -> {
                // 发布供应
                RouteManager.Mine.intentToReleaseSupplyAdd()
            }
            CommonApplyType.LEARNING_CENTER.jumpLink -> {
                // 学习中心
                RouteManager.Main.intentToLearningCenter()
            }
            CommonApplyType.SUPPLY_NEED_LIST.jumpLink -> {
                // 供应商-需求列表
                RouteManager.Mine.intentToSupplyNeedsList()
            }
            CommonApplyType.ADVERTISING.jumpLink -> {
                // 广告宣传
                RouteManager.Main.intentToAdvertising()
            }
            CommonApplyType.MY_SERVER.jumpLink -> {
                // 我的服务
                RouteManager.Service.intentToServiceList()
            }
            CommonApplyType.PERSONNEL_AUDIT.jumpLink ->{
                //人员审核
                RouteManager.Mine.intentToOperatorExamineManager()
            }
            CommonApplyType.REVIEW_SUBMISSION_RECORD.jumpLink ->{
                //审核提交记录
                RouteManager.Mine.intentToExamineRecord()
            }
        }
    }

    override fun initViewObservable() {
        super.initViewObservable()
        observe(mViewModel.userInfoDataEvent) {
            //初始化融云
            it?.let { it1 -> initRongIM(it1) }
        }
        observe(mViewModel.allRongContactListEvent) {
            if (it != null && it.size != 0) {
                refreshRongUserInfo(it)
            }
        }
        observe(mViewModel.groupListEvent) {
            if (it != null) {
                refreshRongGroupInfo(it)
            }
        }
    }

    private fun initRongIM(result: UserInfoVO) {
        Logs.d("token......"+result.ryToken)
        //连接融云
        RongIM.connect(result.ryToken,
            object : RongIMClient.ConnectCallback() {
                override fun onSuccess(userId: String) {
                    Logs.d("re融云连接成功=")
                    // 登录成功，跳转到默认会话列表页。
                    RouteUtils.registerActivity(
                        RouteUtils.RongActivityType.ConversationActivity,
                        ConversationActivity::class.java
                    )
                }

                override fun onError(connectionErrorCode: RongIMClient.ConnectionErrorCode) {
                    Logs.d("re融云连接失败$connectionErrorCode")
                }

                override fun onDatabaseOpened(databaseOpenStatus: RongIMClient.DatabaseOpenStatus) {}
            })


    }

    private fun refreshRongUserInfo(friendList: List<ContactUserVo>) {
        //融云IM -> 用户信息提供者
        //加载自己的用户信息
        RongIM.getInstance().refreshUserInfoCache(
            io.rong.imlib.model.UserInfo(
                mViewModel.mModel.getUserData()?.userUnitId,
                mViewModel.mModel.getUserData()?.userName,
                Uri.parse(mViewModel.mModel.getUserData()?.avatar)
            )
        )
        for (i in friendList.indices) {
            //后台拿到的联系人列表id 比对 融云id相同则缓存
            val userInfo = io.rong.imlib.model.UserInfo(
                friendList[i].userUnitId.toString(),
                friendList[i].userName,
                Uri.parse(friendList[i].avatar)
            )
            //通过网络请求动态加载用户信息
            RongIM.getInstance().refreshUserInfoCache(userInfo)
            Logs.d("re缓存用户信息成功：" + userInfo)
        }
    }

    private fun refreshRongGroupInfo(friendList: List<RongGroupVO>) {
        //融云IM -> 刷新群组信息
        for (i in friendList.indices) {
            //后台拿到的联系人列表id 比对 融云id相同则缓存
            val group = io.rong.imlib.model.Group(
                friendList[i].id,
                friendList[i].name,
                Uri.parse("")
            )
            //通过网络请求动态加载群信息
            RongIM.getInstance().refreshGroupInfoCache(group)
            Logs.d("re缓存群聊信息成功：" + group)
        }
    }

}